import json
import time
import requests
class TCoApi:
    def __init__(self):
        self.config= {
            "apiUrl":"https://intl.fusionsolar.huawei.com/thirdData",
            "apiUid":"江苏综集电建设有限公司",
            "apiPwd":"Zpw921061.",
            "stationCode":"NE=34248273",
            "devTypeId":1,
            "devIds":"1000000034248300,1000000034248279,1000000034248275,1000000034248298,1000000034248277,1000000034248294,1000000034248296,1000000034248292,1000000034248290,1000000034248286,1000000034248288,1000000034248306,1000000034248284,1000000034248304,1000000034248282",

        }
        self.token = ""
        self.tokenTm = 0
        self.devs=[]
        self.devIds=""

        self.readInfo ={}

    def login(self):
        res = True
        try:
            self.token = ""
            self.tokenTm = time.time()
            _url = "/".join([self.config['apiUrl'] , "login"])
            _data ={
                "userName": self.config['apiUid'],
                "systemCode": self.config['apiPwd']
            }
            _header ={
                "Content-Type":"application/json;charset=UTF-8"
            }
            _jsonData = json.dumps(_data)
            response = requests.post(_url, _jsonData, headers=_header)
            if response.status_code==200 :
                content = json.loads(response.content)
                if "success" in  content.keys() and content["success"]:
                    token = response.headers['xsrf-token']
                    self.token = token
                    self.tokenTm = time.time()
                    res = True
                    print('login success. token:' , token)
                else:
                    print(response.content)
        except Exception as er:
            print(er)
        return  res

    def callApi(self, apiKey , params=None):
        res ={}
        try:
            _url = "/".join([self.config['apiUrl'] , apiKey])
            _header ={
                "Content-Type":"application/json;charset=UTF-8",
                "XSRF-TOKEN": self.token
            }
            _jsonData = ""
            if params!=None and len(params.keys())>0:
                _jsonData = json.dumps(params)
            response = requests.post(_url, _jsonData, headers=_header)
            resp = json.loads(response.content)
            if "failCode" in resp.keys() and resp["failCode"]==305:
                self.login()
                res = self.callApi(apiKey , params)
            if "failCode" in resp.keys() and resp["failCode"] == 0:
                res = resp['data']
        except Exception as er:
            print(er)
        return  res
    def getStationRealKpi(self ):
        res ={}
        try:
            ps ={
                "stationCodes":self.config['stationCode']
            }
            res = self.callApi("getStationRealKpi", ps)
        except Exception as er:
            print(er)
        return  res
    def getDevList(self ):
        res =[]
        try:
            ps ={
                "stationCodes":self.config['stationCode']
            }
            devs = self.callApi("getDevList", ps)
            def filterFn (item):
                return item['devTypeId']==1
            res = list(filter(filterFn , devs))
        except Exception as er:
            print(er)
        return  res
    def getStationRealKpi(self):
        res ={}
        try:
            ps ={
                "stationCodes":self.config['stationCode']
            }
            res = self.callApi("getStationRealKpi", ps)
        except Exception as er:
            print(er)
        return  res
    def getDevRealKpi(self):
        res ={}
        try:
            ps ={
                "devIds":self.devIds ,
                "devTypeId": self.config['devTypeId']
            }
            res = self.callApi("getDevRealKpi", ps)
        except Exception as er:
            print(er)
        return  res
    def init(self):
        try:
            self.devs = self.getDevList()
            self.devIds = ",".join([str(x['id']) for x in self.devs])
        except Exception as er:
            print(er)
    def updateRealInfo(self):
        try:
            res ={
                "updatetm": time.time()
            }
            st=self.getStationRealKpi()[0]
            res['stationCode'] = st['stationCode']
            for k , v in st['dataItemMap'].items():
                res[k] = v
            res['devs']={}
            devs = self.getDevRealKpi()
            for d in devs:
                dev ={
                    "devId": d["devId"]
                }
                for ki,vi in d['dataItemMap'].items():
                    dev[ki] = vi
                    res['devs'][dev['devId']] = dev

            self.readInfo = res
        except Exception as er:
            print(er)

api = TCoApi()
api.init()

r=api.updateRealInfo()
print(r)